import os
import cv2

class ImageToVideo:
    def __init__(self, input_folder=None, output_folder=None, frame_time=0.15):
        self._input_folder = input_folder
        self._output_folder = output_folder if output_folder else r"C:\Users\33720\Desktop"
        self._frame_time = frame_time  # 单位：秒

    # ===== Setter 方法 =====
    def set_input_folder(self, folder_path):
        self._input_folder = folder_path

    def set_output_folder(self, folder_path):
        self._output_folder = folder_path

    def set_frame_time(self, time_sec):
        self._frame_time = time_sec

    # ===== 主方法 =====
    def make_video(self, output_filename="output.mp4"):
        if not self._input_folder:
            raise ValueError("请先设置输入文件夹路径")
        if not os.path.exists(self._input_folder):
            raise FileNotFoundError(f"输入文件夹不存在: {self._input_folder}")

        # 获取图片列表，按文件名排序
        images = sorted([f for f in os.listdir(self._input_folder)
                         if f.lower().endswith(('.png', '.jpg', '.jpeg'))])

        if not images:
            raise ValueError("输入文件夹中没有找到图片文件")

        # 读取第一张图片确定尺寸
        first_image_path = os.path.join(self._input_folder, images[0])
        frame = cv2.imread(first_image_path)
        height, width, layers = frame.shape

        # 输出视频路径
        output_path = os.path.join(self._output_folder, output_filename)

        # 帧率 fps = 1 / 每帧时间
        fps = 1 / self._frame_time

        # 创建视频写入对象
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        video = cv2.VideoWriter(output_path, fourcc, fps, (width, height))

        # 写入每一帧
        for img_name in images:
            img_path = os.path.join(self._input_folder, img_name)
            frame = cv2.imread(img_path)
            if frame.shape[0] != height or frame.shape[1] != width:
                # 调整尺寸一致
                frame = cv2.resize(frame, (width, height))
            video.write(frame)

        video.release()
        print(f"视频已生成: {output_path}")
        return output_path
# obj=ImageToVideo()
# obj.set_input_folder(r"C:\Users\33720\Desktop\temp\divide\3\1-1")
# # obj.set_output_folder(r"C:\Users\33720\Desktop\temp")
# obj.make_video()